#include "stdafx.h"
#include "SoundWAV.h"
using namespace System::IO;

namespace Reign
{namespace Audio
{namespace XAudio
{
	#pragma region Constructors
	SoundWAV::SoundWAV(DisposableI^ parent, string^ fileName, int instanceCount, bool looped)
	: SoundWAVI(parent, fileName)
	{
		null();

		try
		{
			audio = parent->FindParentOrSelfWithException<Audio^>();;

			waveFormat = new WAVEFORMATEX();
			ZeroMemory(waveFormat, sizeof(WAVEFORMATEX));
			waveFormat->wFormatTag = formatCode;
			waveFormat->nChannels = channels;
			waveFormat->nSamplesPerSec = sampleRate;
			waveFormat->nAvgBytesPerSec = formatAvgBytesPerSec;
			waveFormat->nBlockAlign = formatBlockAlign;
			waveFormat->wBitsPerSample = bitDepth;
			waveFormat->cbSize = formatExtraSize;

			pin_ptr<void> dataPtr = &data[0];
			buffer = new byte[data->Length];
			memcpy(buffer, dataPtr, data->Length);
			bufferLength = data->Length;
			data = nullptr;

			for (int i = 0; i != instanceCount; ++i)
			{
				inactiveInstances->AddLast(gcnew SoundWAVInstance(this, looped));
			}

			audio->UpdateCallback += gcnew Audio::UpdateCallbackFunc(this, &SoundWAV::Update);
		}
		catch (Exception^ e)
		{
			delete this;
			throw e;
		}
	}

	SoundWAV::~SoundWAV()
	{
		disposeChilderen();
		if (audio) audio->UpdateCallback -= gcnew Audio::UpdateCallbackFunc(this, &SoundWAV::Update);

		if (waveFormat) delete waveFormat;
		if (buffer) delete buffer;
		null();
	}

	void SoundWAV::null()
	{
		buffer = 0;
		waveFormat = 0;
	}
	#pragma endregion
}
}
}